package com.shop.util;

import com.shop.exception.DAOException;

import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;

public class ReturnImg {

    private static String checkImg(String path) {
        String suffix = null;
        suffix = path.trim().substring(path.lastIndexOf(".")+1);
        String format = null;

        switch(suffix) {
            case "jpe":
            case "jpeg":
            case "jpg": format = "image/jpeg"; break;
            case "png": format = "image/png"; break;
            case "webp": format = "image/webp"; break;
        }

        return format;
    }

    public static void returnImg(HttpServletResponse resp, String path) throws DAOException {
        FileInputStream fis = null;
        try {
            fis = new FileInputStream(path);
            //得到文件大小
            int size = fis.available();
            byte data[] = new byte[size] ;
            fis.read(data) ;
            fis.close();

            //设置返回的文件类型
            String suffix = checkImg(path);
            if(suffix == null) {
                throw new DAOException();
            }
            resp.setContentType(suffix);
            OutputStream os = resp.getOutputStream() ;
            os.write(data);
            os.flush();
            os.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
